package com.campsys.filter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.campsys.core.Result;
import com.campsys.domain.LoginUser;
import com.campsys.util.JWTUtil;
import com.campsys.util.RedisUtil;
import org.apache.tomcat.util.http.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        //如果token为空，进入下一个服务器
        if(token == null){
            filterChain.doFilter(request,response);
            return;
        }

        //验证token
        boolean b = JWTUtil.verifyToken(token);
        logger.info("验证token:" + b);
        if (!b) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(Result.error("Token不合法")));
            return;
        }

        //获取用户信息
        Long userId = JWT.decode(token).getClaim("userId").asLong();

        LoginUser loginUser = redisUtil.getCacheObject("user:" + userId);

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);

    }
}
